#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os

import MySQLdb as mdb
import sys
conn = mdb.connect(host='127.0.0.1',
                       user='root',
                       passwd ='123456',
                       db='test')
cur = conn.cursor()
def create():
    sql_create_table='create table Images(id int primary key auto_increment,data mediumblob)'
    try:
        cur.execute(sql_create_table)
        print("success to create table")
    except:
        print("fail to create table")
def insert():
    try:
        fin =open('test.jpg')
        img = fin.read()
        fin.close()
    except Exception as e:
        print("error %d:%s"%(e.args[0],e.args[1]))
        sys.exit(1)
    try:
        print("string",mdb.escape_string(img))
        sql_insert="insert into Images set data=%s" %mdb.escape_string(img)
        cur.execute("INSERT INTO Images SET Data='%s'" %
mdb.escape_string(img))
        print("success insert")
        conn.commit()
        cur.close()
        conn.close()
    except mdb.Error,e:
        print("error %d:%s"%(e.args[0],e.args[1]))
        sys.exit()

def query():
    try:
        sql_query="select data from Images"
        cur.execute(sql_query)
        path ="image.png"
        fout = open(path,"wb")
        print(cur.fetchone()[0])
        fout.write(cur.fetchone()[0])
        fout.close()
        cur.close()
        conn.close()
    except IOError,e:
        delete_file(path)
        print("error %d:%d"%(e.args[0],e.args[1]))
        sys.exit()
def delete_file(path):
    if os._exists(path):
        os.remove(path)
    else:
        print("not exist such file")

query()

#insert()



